package com.twopointer;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 三数相加
 * 外层遍历
 * 内层 双指针
 * O(n2)
 */
public class ThreeSumEx {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        if (nums == null || nums.length <= 2) return result;

        int length = nums.length;
        Arrays.sort(nums);
        for (int i = 0; i < length - 2; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) continue;

            int left = i + 1;
            int right = length - 1;
            while (left < right) {
                if (nums[left] + nums[right] + nums[i] == 0) {
                    List<Integer> list = new ArrayList<>();
                    list.add(nums[i]);
                    list.add(nums[left]);
                    list.add(nums[right]);
                    result.add(list);
                    left++;
                    right--;
                    while (left < right && nums[left] == nums[left - 1]) {
                        left++;
                    }
                    while (left < right && nums[right] == nums[right + 1]) {
                        right--;
                    }
                }else if (nums[left] + nums[right] + nums[i] > 0){
                    right--;
                }else
                    left++;
            }
        }
        return result;
    }
}
